<template>
  <div style="margin-top: 16px">
    <el-form-item label="相对关系">
      <el-select v-model="userTaskForm.assignee" @change="updateElementTask('assignee')" clearable filterable >
        <el-option v-for="item in postList" :key="item.value" :label="item.name" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="选择用户">
      <!-- <el-select v-model="userTaskForm.candidateUsers" multiple collapse-tags @change="updateElementTask('candidateUsers')" clearable filterable >
        <el-option v-for="item in userList" :key="item.userId" :label="`${item.dept.deptName}-${item.nickName}`" :value="item.userName" />
      </el-select> -->
      <el-button @click="selectUser">添加人员</el-button>
      <div>
        <el-tag v-for="(user,index) in candidateUsers" :key="index" closable  @close="closeTag(user)">
           {{user.nickName}}
        </el-tag>
      </div>
      <user-select ref="userSelect" @saveUsers="saveUsers"></user-select>
    </el-form-item>
    <!-- <el-form-item label="候选岗位">
      <el-select v-model="userTaskForm.candidateGroups" multiple collapse-tags @change="updateElementTask('candidateGroups')" clearable filterable >
        <el-option v-for="gk in mockData" :key="'ass-' + gk" :label="`分组${gk}`" :value="`group${gk}`" />
      </el-select>
    </el-form-item>
    <el-form-item label="到期时间">
      <el-input v-model="userTaskForm.dueDate" clearable @change="updateElementTask('dueDate')" />
    </el-form-item>
    <el-form-item label="跟踪时间">
      <el-input v-model="userTaskForm.followUpDate" clearable @change="updateElementTask('followUpDate')" />
    </el-form-item>
    <el-form-item label="优先级">
      <el-input v-model="userTaskForm.priority" clearable @change="updateElementTask('priority')" />
    </el-form-item> -->
  </div>
</template>

<script>
import { listPost } from "@/api/flowable/front";
import { createListenerObject, updateElementExtensions } from "../../../utils";
import  UserSelect from "@/components/UserSelect";

export default {
  name: "UserTask",
  props: {
    id: String,
    type: String
  },
  inject: {
    prefix: "prefix"
  },
  components:{UserSelect},
  data() {
    return {
      defaultTaskForm: {
        assignee: "",
        candidateUsers: [],
        candidateGroups: [],
        // dueDate: "",
        // followUpDate: "",
        // priority: "",
        text:[]
      },
      userTaskForm: {},
      // mockData: ['starter_deptLeader','admin', 'test'],
      // specialUser:[
      //   {nickName:'发起者',userName:'${starter}',dept:{deptName:''}},
      //   {nickName:'部门主管',userName:'STARTER_DEPTLEADER',dept:{deptName:'发起者'}}
      // ],
      // userList:[],//人员列表
      postList:[{name:'发起者-发起者',value:'${starter}'},{name:'多实例用户',value:'${assignee}'}],//岗位列表
      candidateUsers:[],
    };
  },
  watch: {
    id: {
      immediate: true,
      handler() {
        this.bpmnElement = window.bpmnInstances.bpmnElement;
        this.$nextTick(() => this.resetTaskForm());

        //创建时候默认添加两个监听器
        let listener = {
          class: 'com.ruoyi.flowable.listener.UserTaskListener',
          event: 'create',
          listenerType: "classListener"
        };
        let create = createListenerObject(listener, true, this.prefix);
        listener.event = 'complete';
        let complete = createListenerObject(listener, true, this.prefix);
        updateElementExtensions(this.bpmnElement, [create,complete]);

      }
    }
  },
  created(){
    this.getPosts();
    // this.getUsers();
  },
  methods: {
    resetTaskForm() {
      // console.log(this.bpmnElement);
      this.candidateUsers = []; //初始化显示
      for (let key in this.defaultTaskForm) {
        let value;
        if (key === "candidateUsers" || key === "candidateGroups") {
          value = this.bpmnElement?.businessObject[key] ? this.bpmnElement.businessObject[key].split(",") : [];
        } else if(key === "text" && this.bpmnElement?.businessObject[key]) {
          if(Array.isArray(this.bpmnElement.businessObject[key])){
            value = this.bpmnElement.businessObject[key] || this.defaultTaskForm[key];
          } else {
            value = this.bpmnElement.businessObject[key].split(",");
          }
        } else {
          value = this.bpmnElement?.businessObject[key] || this.defaultTaskForm[key];
        }
        this.$set(this.userTaskForm, key, value);
      }
      if(this.userTaskForm.candidateUsers && this.userTaskForm.text){
        this.userTaskForm.candidateUsers.forEach((item, index)=>{
          this.candidateUsers.push({userName:item, nickName: this.userTaskForm.text[index]})
        })
      }
    },
    updateElementTask(key) {
      const taskAttr = Object.create(null);
      if (key === "candidateUsers" || key === "candidateGroups") {
        taskAttr[key] = this.userTaskForm[key] && this.userTaskForm[key].length ? this.userTaskForm[key].join() : null;
      } else {
        taskAttr[key] = this.userTaskForm[key] || null;
      }
      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, taskAttr);
    },
    selectUser(){
        this.$refs['userSelect'].open = true;
    },
    getPosts(){
      listPost().then(res=>{
        res.data.forEach(item => {
          let namePrefix = item.bindDept == 'Y'? '部门岗位-':'岗位-';
          let idPrefix = item.bindDept == 'Y'? 'STARTER_DEPT_POST__':'STARTER_POST__';
          this.postList.push({name:  namePrefix + item.postName, value: idPrefix + item.postId, })
        });
      })
    },
    // getUsers(){
    //   listUser({pageNum:1,pageSize:100}).then(res=>{
    //     this.userList = res.rows;
    //     this.specialUser = this.specialUser.concat(res.rows)
    //   })
    // },
    saveUsers(users){
      let userNames = [];
      let nickNames = [];
      this.candidateUsers = [];
      users.forEach(item =>{
        userNames.push(item.userName);
        nickNames.push(item.nickName +'-'+ item.dept.deptName);
        this.candidateUsers.push({userName:item.userName, nickName:item.nickName +'-'+ item.dept.deptName})
      })
      this.userTaskForm.candidateUsers = userNames;
      this.userTaskForm.text = nickNames;
      this.updateElementTask('candidateUsers');
      this.updateElementTask('text');
    },
    closeTag(user){
      let index = this.candidateUsers.indexOf(user);
      this.candidateUsers.splice(index, 1);
      this.userTaskForm.candidateUsers.splice(index, 1);
      this.userTaskForm.text.splice(index, 1);
      this.updateElementTask('candidateUsers');
      this.updateElementTask('text');
    }
  },
  beforeDestroy() {
    this.bpmnElement = null;
  }
};
</script>
